/*
 * Copyright TLR Team, Inc. All Rights Reserved.
 */
package com.tfb.service.utility;

import com.tfb.rong.Device;
import com.tfb.rong.DeviceDataWithBLOBs;
import com.tfb.rong.Users;
import com.tfb.service.UserAssessmentI;
import com.tlr.device.model.Eban;
import com.tlr.device.model.HealthUser;
import com.tlr.device.rest.AppContext;
import com.tlr.device.service.DeviceDatabaseService;
import com.tlr.device.service.EbanDevice10API;
import com.tlr.device.service.EbanDeviceAPI;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class ReminderHourlyJob implements Job {

    private static final Logger log = Logger.getLogger(ReminderHourlyJob.class);
    private DeviceDatabaseService deviceService;
    private UserAssessmentI userService;

    protected synchronized void initDatabaseService() {
        if (deviceService == null) {
            deviceService = (DeviceDatabaseService) AppContext.getBeanContext().getBean("deviceDatabaseService");
        }
        if (userService == null) {
            userService = (UserAssessmentI) AppContext.getBeanContext().getBean("userAssessmentService");
        }
    }

    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {
        // Used in air map of dashboard
        log.info("Start to update eban point info");
        initDatabaseService();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        EbanDeviceAPI ebanDevice = new EbanDevice10API();
        List<Device> devices = deviceService.getAllDevice(1, 1);
        for (Device device : devices) {
            String token = null;
            try {
                List<Users> users = deviceService.getUserMapper().selectByDeviceUserBind(device.getDevicemac());
                if (users.isEmpty()) {
                    log.error(String.format("The device %s is not binded to a user", device.getDevicemac()));
                    continue;
                }
                Users user = users.get(0);
                HealthUser healthUser = deviceService.getHealthUserMapper().selectByDeviceMac(device.getDevicemac());
                if (healthUser == null) {
                    log.error(String.format("The device %s doesn't have health user", device.getDevicemac()));
                } else {
                    log.info("Reading eban device '" + device.getDevicemac() + "'");
                    token = ebanDevice.openidLogin(user.getWebchat());
                    Eban eban = ebanDevice.getLastDeviceData(token, device.getDevicemac(), sf.format(new Date()));
                    eban.setStorage_id(device.getDeviceid());
                    eban.setAccount(device.getRealname());
                    eban.setNick_name(healthUser.getName());
                    eban.setOwner(healthUser.getName() != null ? healthUser.getName() : "未知名字");
                    eban.setMobile(healthUser.getTel());
                    DeviceDataWithBLOBs ddb = new DeviceDataWithBLOBs();
                    ddb.setDeviceid(eban.getDevice_id()); // car plate here as mac
                    ddb.setLng(eban.getLng());
                    ddb.setLat(eban.getLat());
                    ddb.setPoint(Integer.parseInt(eban.getPoint() != null ? eban.getPoint() : "0"));
                    ddb.setGettime(Calendar.getInstance().getTime());
                    ddb.setDatatype(AppConst.EBAN_POINT_TYPE);
                    ddb.setData(JsonUtil.writeValue(eban));
                    deviceService.insertDeviceDataSelective(ddb);
                    deviceService.deleteDataBefore6Hours(ddb);
                }
                ebanDevice.logoff(token);
            } catch (Exception e) {
                log.error(Utils.getFullException(e));
                ebanDevice.logoff(token);
            }
        }
        log.info("Completed to update eban point info");
    }
}
